//
//  NSObject+TGObject.m
//  指乎
//
//  Created by Dean on 16/8/9.
//  Copyright © 2016年 Dean. All rights reserved.
//

#import "NSObject+TGObject.h"
#import <objc/runtime.h>
static const void *kName = "customProperty";

@implementation NSObject (TGObject)
///获取Window当前显示的视图控制器ViewController
- (UIViewController *)findCurrentShowingViewController{
    //获得当前活动窗口的根视图
       UIViewController *vc = APPDelegate.tabarController;
       UIViewController *currentShowingVC = [self findCurrentShowingViewControllerFrom:vc];
       return currentShowingVC;
}
/**
 *  获取Window当前显示的视图控制器ViewController
 *
 *  @param vc   从哪个界面开始分析
 *
 *  @return 当前显示的视图控制器ViewController
 */
- (UIViewController *)findCurrentShowingViewControllerFrom:(UIViewController *)vc{
    //方法1：递归方法 Recursive method
       UIViewController *currentShowingVC;
       if ([vc presentedViewController]) { //注要优先判断vc是否有弹出其他视图，如有则当前显示的视图肯定是在那上面
           // 当前视图是被presented出来的
           UIViewController *nextRootVC = [vc presentedViewController];
           currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
           
       } else if ([vc isKindOfClass:[UITabBarController class]]) {
           // 根视图为UITabBarController
           UIViewController *nextRootVC = [(UITabBarController *)vc selectedViewController];
           currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
           
       } else if ([vc isKindOfClass:[UINavigationController class]]){
           // 根视图为UINavigationController
           UIViewController *nextRootVC = [(UINavigationController *)vc visibleViewController];
           currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
           
       } else {
           // 根视图为非导航类
           currentShowingVC = vc;
       }
       
       return currentShowingVC;
}



#pragma mark - 字符串类型的动态绑定
- (NSString *)customProperty {
    return objc_getAssociatedObject(self, kName);
}

- (void)setCustomProperty:(NSString *)name {
    objc_setAssociatedObject(self, kName, name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

#pragma mark - log all property
-(NSString*)ldPrintAllPropertys
{
#ifdef DEBUG
    NSMutableString* sb = [NSMutableString stringWithFormat:@"<%@> \n", [self class]];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        
        [sb appendFormat:@" %@ : %@ \n",propertyName,[self valueForKey:propertyName]];
    }
    free(properties);
    NSLog(@"%@",sb);
    return sb;
#else
    return nil;
#endif
}
- (UINavigationController *)getNavigationVC {
    UITabBarController *tab = (UITabBarController *)APPDelegate.window.rootViewController;
    TGBaseNavigationVC *nav = tab.selectedViewController;
    UIViewController *showNav = [nav getCurrentViewController];
    UINavigationController *n =(UINavigationController *) showNav.presentedViewController;
    if (n && [n isKindOfClass:[UINavigationController class]]) {
        return (UINavigationController *)showNav.presentedViewController;
    }else
    {
        return nav;
    }
    
}
-(UIViewController *)getNewCurrentVC{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication].delegate window];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC = window.rootViewController;
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        //多层present
        while (appRootVC.presentedViewController) {
            appRootVC = appRootVC.presentedViewController;
            if (appRootVC) {
                nextResponder = appRootVC;
            }else{
                break;
            }
        }
        //        nextResponder = appRootVC.presentedViewController;
    }else{
        
        //        NSLog(@"===%@",[window subviews]);
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //        UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    
    if (![result isKindOfClass:[UIViewController class]]) {
        return [self findCurrentShowingViewController];
    }
    return result;
}

- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}
-(NSString *)decimalNumberWithDouble{
    
    if ([self isKindOfClass:[NSString class]] || [self isKindOfClass:[NSNumber class]]) {
        NSString * str =(NSString *)self;
        NSString *doubleString        = [NSString stringWithFormat:@"%lf", str.doubleValue];
        NSDecimalNumber *decNumber    = [NSDecimalNumber decimalNumberWithString:doubleString];
        return [decNumber stringValue];
    }
    return (NSString *)self;
}
//ios 自带转换json
-(NSString *) objectToJSON
{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (error)
    {
        NSLog(@"error ->%@",error);
        return @"";
    }
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
+(id)jsonToObject:(id)data error:(NSError **)error
{
    if (!data || data == (id)kCFNull) return nil;
    
    NSData *jsonData = nil;
    
    if ([data isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)data dataUsingEncoding : NSUTF8StringEncoding];
    } else if ([data isKindOfClass:[NSData class]]) {
        jsonData = data;
    }else if ([data isKindOfClass:[NSDictionary class]] || [data isKindOfClass:[NSArray class]]){
        return data;
    }
    if (jsonData==nil) {
        return nil;
    }
    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:error];
    return jsonObj;
}
+(id)jsonToObject:(id)data
{
    

    NSError *error = nil;
    id jsonData  =[self jsonToObject:data error:&error];
    if (error)
    {
        NSLog(@"error ->%@",error);
        return @"";
    }
    return jsonData;
}
-(NSString *)toString {
    if (self==nil || [self isKindOfClass:[NSNull class]]) {
        return @"";
    }
    return [NSString stringWithFormat:@"%@",self];
}

@end
